package com.hxl.tech.gateway.auth.util;


import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class StringUtil {

    /**
     * 匹配_加任意一个字符
     */
    private static final Pattern UNDER_LINE_PATTERN = Pattern.compile("_(\\w)");

    /**
     * 驼峰转蛇形
     */
    public static String camelToUnderline(String source) {
        if (source == null || "".equals(source.trim())) {
            return "";
        }
        int len = source.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = source.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append("_");
                sb.append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 蛇形转驼峰
     *
     * @param source
     * @return
     */
    public static String underLineToCamel(String source) {
        Matcher matcher = UNDER_LINE_PATTERN.matcher(source);
        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(result, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(result);
        return result.toString();
    }

}
